<?php
namespace Erp\C\Orders\Tn\Shipping;
use Erp\C\Orders\Tn\Shipping\Shipping;
use Erp\C\Orders\Tn\Api\ApiYdModule;
use Fn;
/**
 * 义达日本专线
 */
class Yd extends Shipping
{
    private $api_yd;
    //初始化API请求对象
    public function __construct()
    {
        $this->api_yd = new ApiYdModule();
    }
    //获取跟踪号入口方法
    public function getTn($Orders)
    {
        if (!is_array($Orders)) {
            $Orders = array($Orders);
        }
        $count = count($Orders);
        //订单调用量，一次调用的订单数量，提下传几个订单可以提高效率
        $multi_num = 5;
        $for_num = ceil($count/$multi_num);
        for ($i=0; $i < $for_num; $i++) {
            $s = $for_num*$i;
            $tmp_arr = array_slice($Orders,$s,$multi_num);
            $this->ydApiMgr($tmp_arr);
        }
    }
    public function ydApiMgr($tmp_arr){
        $request_data = $this->createPackageParams($tmp_arr);//拼接数据
        Fn\App::Log('get_YdTn',$request_data,'获取TN数据');
        $response = $this->api_yd->createAndConfirmPackages($request_data); //Api接口业务转化
        Fn\App::log('get_YdTn',$response,'获取Tn数据');
        $this->disposePackageReturn($response);//返回的结果数据处理
    }
    /**
     * 提交数据
     *创建线上包裹数据格式
     *@param array $tmp_arr
     *@return array
     */
    public function createPackageParams($tmp_arr){
        $o_model = A('Orders');
        $multi_request = array();
        foreach ($tmp_arr as $k => $ordersId) {
            $orderInfo = $o_model->combinOrderInfo($ordersId);//获取订单信息
            $reference_no = $ordersId; //客户参考号
            $shipping = $orderInfo['orders_shipping_method'];//运输方式
            // 运输方式转换 :ERP代码 ---->API标准代码
            $shippingArr = $this->_shippingEnumerate($shipping);
            $shipping = $shippingArr['shipCode'];
            $header = $shippingArr['header'];
            //收货地址，进行拼接
            $address1 = $orderInfo['orders_delivery_address']." ";//收货人详细地址
            $address2 = $orderInfo['orders_delivery_address2'];//收货人详细地址2
            $address = $address1.' '.$address2;
            //一个订单内的所有产品信息
            $productList = $orderInfo['orders_items'];
            $count = 0;
            $price = 0;
            foreach ($productList as $orderProduct){
                $count += $orderProduct['orders_product_quantity'];
                $price += $orderProduct['orders_item_total_price_usd'];
            }
            $unitPrice = $price/$count;
            $unitPrice = round($unitPrice,4);
            $invoice = array(); //海关申报信息(发票)
            foreach ($productList as $key => $orderProduct) {
                $productId=$orderProduct['product_id'];
                $CustomsInfo=$this->getRealCustomsName($productId);	//报关名
                $categoryEnDesc	= $CustomsInfo['ClassnameForCustoms'];//报关英文名
                $invoice[$key]=array(
                    'invoice_enname'		=> $categoryEnDesc,//英文品名
                    'invoice_quantity'		=> $count,//数量
                    'invoice_unitcharge'	=> $unitPrice,//单价
                );
                break;
            }
            //拼接数据开始
            $paramsArr = array(
                'reference_no'		=> $reference_no,//客户参考号
                'shipping_method'	=> $shipping,//运输方式
                //发件人信息
                'shipper'			=> array(
                    'shipper_name'			=> 'Jun Wang',//发件人姓名
                    'shipper_countrycode'	=> 'CN',//发件人国家二字码
                    'shipper_street'		=> '3th floor,logistical Building B, Yihong Road, Yantian Village guangdong sheng   dongguan shi  feng gang zhen',//发件人地址
                    'shipper_telephone'		=> '0755-25672819-8010',//发件人电话
                    'shipper_postcode'      => '523701'//发件人邮编
                ),
                //收件人信息
                'consignee'			=> array(
                    'consignee_name'		=> $orderInfo['orders_delivery_name'],//收件人姓名
                    'consignee_countrycode'	=> $orderInfo['orders_delivery_country_iso'],//收件人国家代码
                    'consignee_street'		=> $address,//收件人地址
                    'consignee_telephone'	=> $orderInfo['orders_delivery_tel'],//收件人电话
                ),
                'invoice'			=> $invoice //海关申报信息
            );
            $paramsJson = json_encode($paramsArr);
            //拼接数据结束
            $arr = 'paramsJson='.$paramsJson.'&appToken='.$this->api_yd->appToken.'&appKey='.$this->api_yd->appKey.'&serviceMethod=createorder';
            $multi_request[$ordersId] = array('post'=>$arr,'header'=>$header,'url'=>$this->api_yd->url);
            unset($res);unset($content);
        }
        return $multi_request;
    }
    //ERP运输方式转换成API标准的运输方式
    private function _shippingEnumerate($name){
        switch($name){
            case 'YDJP_TN':
                return array('shipCode'=>'JP-DS','shipperAddrCode'=>'','warehouseCode'=>'','header'=>$this->api_yd->header);
            default:
                return false;
        }
    }
    /**
     * 获取Lable入口
     * @param array $orders 一维数组
     */
    public function getLable($orders){
        $this->_getpdf($orders);
    }
    /**
     *获取tn成功后调用此方法获取面单Pdf
     *@param array $orders 一维数组订单号
     */
    public function _getpdf($orders){
        if(!$orders){
            echo "无订单".__LINE__;
        }
        $this->_requestLable($orders);//获取Lable标签
    }

    /**
     * 返回结果集处理
     *处理提交包裹所返回的响应
     *@param array $multi_request_res
     *	1:"待取TN",
     *	6:"TN失败",
     *	7:"已取TN",
     *	8:"PDF失败"
     *	99: 成功
     */
    public function disposePackageReturn($multi_request_res)
    {
        if ($multi_request_res) {
            foreach ($multi_request_res as $k => $v) {
                if (!is_array($v)) {
                    $v = json_decode($v,true);
                }
                $ordersStatus = A('Orders')->getOrdersStatus($k);
                if ($v['success'] == 1 && isset($v['success'])) {
                    $ordersData = array();
                    $ordersData['orders_tn'] = $v['data']['shipping_method_no'];
                    if(!$ordersData['orders_tn'])continue;
                    if($ordersStatus == '300'){
                        $ordersData['orders_status_children'] = 7;
                    }
                    A('Orders')->saveData($ordersData,$k);
                    A('Orders')->saveOrderHistory($k,"获取义达日本专线TN成功--".$ordersData['orders_tn']);
                }else{
                    $errorsMsgs = $v['cnmessage'];
                    $return = strpos($errorsMsgs,'参考号码已经存在');
                    if($return !== false){
                        $this->_findTn($k);
                        continue;
                    }
                    $ordersData = array();
                    $errorsMsgs = $v['cnmessage'];
                    if($ordersStatus == '300'){
                        $ordersData['orders_status_children'] = 6;
                        A('Orders')->saveData($ordersData,$k);
                    }
                    A('Orders')->saveOrderHistory($k,"获取义达日本专线TN失败--".$errorsMsgs);
                }
            }
        }
    }
    /**
     *已经生成过TN的订单会调用此方法查询该订单对应的TN号
     *@param   string $Orderid  字符串 传入订单号
     */
    //重复订单到这里
    private function _findTn($orderid){
        $response = $this->api_yd->findTnCreatePackage($orderid);
        $this->disposeFindPackageReturn($response);//设置响应信息
    }
    /**
     * @param $response
     * @param $order_id
     * @return mixed
     * 重复TN保存到orders表
     */
    public function disposeFindPackageReturn($response){
        foreach ($response as $k=>$v){
            $v = json_decode($v,true);
            $ordersStatus = A('Orders')->getOrdersStatus($k);
            if ($v['success'] == 1 && isset($v['success'])) {
                $ordersData = array();
                $ordersData['orders_tn'] = $v['data'][0]['server_hawbcode'];
                if(!$ordersData['orders_tn'])continue;
                if($ordersStatus == '300'){
                    $ordersData['orders_status_children'] = 7;
                }
                A('Orders')->saveData($ordersData,$k);
                A('Orders')->saveOrderHistory($k,"获取义达日本专线TN成功--".$ordersData['orders_tn']);
            }else{
                $ordersData = array();
                $errorsMsgs = $v['cnmessage'];
                if($ordersStatus == '300'){
                    $ordersData['orders_status_children'] = 6;
                    A('Orders')->saveData($ordersData,$k);
                }
                A('Orders')->saveOrderHistory($k,"获取义达日本专线TN失败--".$errorsMsgs);
            }
        }
    }
    /**
     * @param $response
     * 面单接口请求，配置参数
     */
    private function _requestLable($response){
        $oModel=A("Orders");
        $res = $oModel->getOrders($response);
        $root_dir = "./Public/Data/Files/";
        foreach ($res as $k=>$v) {
            $ordersId = $v['orders_id'];
            $time = $v['orders_import_time'];
            $dir_local_root = $root_dir.date('Ymd',$time)."/";
            $filename = $ordersId.'.pdf';
            //删除PDF
            if(file_exists($dir_local_root.$filename)){
                @unlink($dir_local_root.$filename);
            }
            //面单拼接数据开始
            $paramsArr = array(
                'configInfo' => array(
                    'lable_file_type' => '2',//标签文件类型 1 ：PNG文件 2 ：PDF文件
                    'lable_paper_type'=> '1',//	纸张类型 1 ：标签纸(10*10厘米) 2 ：A4纸(21*29.7厘米)
                    'lable_content_type'=> '1',//标签内容类型代码1:标签2:报关单3:配货单4:标签+报关单5:标签+配货单6 ：标签+报关单+配货单
                    'additional_info'=>array(
                        'lable_print_invoiceinfo'=>'N',
                        'lable_print_buyerid'=>'N',
                        'lable_print_datetime'=>'Y',
                        'customsdeclaration_print_actualweight'=>'N'
                    )
                ),
                'listorder'=>array(
                    array(
                        'reference_no'=>$ordersId //自己平台订单号
                    ),
                )
            );
            $paramsJson = json_encode($paramsArr);
            $arr = 'paramsJson='.$paramsJson.'&appToken='.$this->api_yd->appToken.'&appKey='.$this->api_yd->appKey.'&serviceMethod=getnewlabel';
            $response = $this->api_yd->createPackageLable($arr);
            if (!is_array($response)) {
                $response = json_decode($response,true);
            }else{
                $response = $this->xmlDecode($response,true);
                $response = $response['val'];
            }
            $contentUrl = $response['data'][0]['lable_file'];
            $content = file_get_contents($contentUrl);
            $is_exists = $this->saveShippingLable($dir_local_root,$filename,$content);
            Fn\App::log('yd_Dff_error',array(
                        'response'=>$response,
                        'isExists'=>$is_exists,
                        'url'=>$dir_local_root.$filename
                        ),"义达请求PDF调试");

            if(!$is_exists){
                sleep(2);
                $header = 'Content-Type:application/x-www-form-urlencoded;charset=utf-8';
                $response = $this->api_yd->createPackageLable($arr,$header);
                if (!is_array($response)) {
                    $response = json_decode($response,true);
                }else{
                    $response = $this->xmlDecode($response,true);
                    $response = $response['val'];
                }
                $contentUrl = $response['data'][0]['lable_file'];
                $content = file_get_contents($contentUrl);
                $is_exists = $this->saveShippingLable($dir_local_root,$filename,$content);
            }
            if($is_exists){
                $saveData = array();
                $saveData['orders_pdf_exist'] = 1;
                $ordersStatus = $res[$k]['orders_status'];
                if($ordersStatus == '300'){
                    $saveData['orders_status_children'] = 99;
                }
                $oModel->saveData($saveData,$res[$k]['orders_id']);
                A('Orders')->saveOrderHistory($ordersId,'获取义达PDF成功');
            }else{
                $saveData = array();
                $ordersStatus = $res[$k]["orders_status"];
                if($ordersStatus == '300'){
                    $saveData['orders_status_children'] = 8;
                }
                $oModel->saveData($saveData,$res[$k]['orders_id']);
                A('Orders')->saveOrderHistory($ordersId,'获取义达PDF失败');
            }
        }
    }
}





